<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" clearable placeholder="请输入名称" style="width: 240px" @change="handQuery" />
      </el-form-item>
      <el-form-item label="创建时间" prop="dateRange" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          value-format="YYYY-MM-DD"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="itemList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center" width="50" />
      <el-table-column align="center" label="序号" width="50" v-if="columns.id.visible">
        <template #default="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="name" align="center" label="名称" :show-overflow-tooltip="true" v-if="columns.name.visible"></el-table-column>
      <el-table-column prop="avatar" align="center" label="图片" v-if="columns.avatar.visible">
        <template #default="scope">
          <el-image
            v-if="scope.row.avatar"
            style="height: 60px"
            :src="scope.row.avatar"
            fit="cover"
            :preview-src-list="[scope.row.avatar]"
            :preview-teleported="true"
          />
          <span v-else>暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column prop="description" align="center" label="描述" :show-overflow-tooltip="true" v-if="columns.description.visible"></el-table-column>
      <el-table-column
        prop="serviceContent"
        align="center"
        label="服务内容"
        :show-overflow-tooltip="true"
        v-if="columns.serviceContent.visible"
      ></el-table-column>
      <el-table-column prop="belongToHospitalInfo" align="center" label="所属医院" v-if="columns.belongToHospitalInfo.visible">
        <template #default="scope">
          <el-button type="primary" plain icon="View" @click="handleCheckInfo(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" align="center" label="创建时间" v-if="columns.createTime.visible"> </el-table-column>
      <el-table-column align="center" label="操作" class-name="small-padding fixed-width" v-if="columns.action.visible">
        <template #default="scope">
          <el-tooltip content="分配医院" placement="top">
            <el-button link type="warning" icon="Share" @click="handleAssignHospital(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="编辑" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <el-dialog v-model="open" :title="title" width="600px" append-to-body>
      <!-- 添加或修改项目对话框 -->
      <el-form :model="form" ref="itemRef" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="图片" prop="avatar">
          <image-upload v-model="form.avatar" :limit="1" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" :rows="2" type="textarea" :maxlength="100" show-word-limit resize="none" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="服务内容" prop="serviceContent">
          <el-input v-model="form.serviceContent" :rows="2" type="textarea" :maxlength="100" show-word-limit resize="none" placeholder="请输入服务内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 项目信息对话框 -->
    <HospitalWithPrice 
      :hospitalInfoVisible="hospitalInfoVisible" 
      :hospitalInfoList="currentHospitalInfo" 
      @handleClose="hospitalInfoClose"
    />

    <!-- 分配医院对话框 -->
    <AssignHospital 
      :assignHospitalVisible="assignHospitalVisible" 
      :currentItem="currentItem" 
      @handleClose="assignHospitalClose"
      @handleSuccess="handleAssignHospitalSuccess"
    />
  </div>
</template>

<script setup name="Hospital">
import { listItem, getItem, addItem, updateItem, delItem, getItemHospitalAssignments } from "../../api/item/item";
import HospitalWithPrice from "./components/HospitalWithPrice.vue";
import AssignHospital from "./components/AssignHospital.vue";

const { proxy } = getCurrentInstance();

// 响应式数据
const showSearch = ref(true);
const single = ref(true);
const multiple = ref(true);
const ids = ref([]);
const loading = ref(false);
const itemList = ref([]);
const total = ref(0);
const title = ref("");
const open = ref(false);
const dateRange = ref([]);
const hospitalInfoVisible = ref(false);
const currentHospitalInfo = ref([]);
const assignHospitalVisible = ref(false);
const currentItem = ref({});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    startTime: undefined,
    endTime: undefined,
  },
  rules: {
    name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
    avatar: [{ required: true, message: "图片不能为空", trigger: "blur" }],
    description: [{ required: true, message: "描述不能为空", trigger: "blur" }],
    serviceContent: [{ required: true, message: "服务内容不能为空", trigger: "blur" }],
  },
});

const { form, queryParams, rules } = toRefs(data);

// 列显隐信息
const columns = ref({
  id: { label: "序号", visible: true },
  name: { label: "名称", visible: true },
  avatar: { label: "头像", visible: true },
  description: { label: "描述", visible: true },
  serviceContent: { label: "服务内容", visible: true },
  belongToHospitalInfo: { label: "所属项目", visible: true },
  createTime: { label: "创建时间", visible: true },
  action: { label: "操作", visible: true },
});

const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const handleDelete = (row) => {
  let confirmText = "";
  let itemIds = null;
  if (row.id) {
    const index = itemList.value.findIndex((item) => item.id === row.id);
    confirmText += index + 1 + "、";
    itemIds = row.id;
  } else {
    ids.value.forEach((id) => {
      const index = itemList.value.findIndex((item) => item.id === id);
      confirmText += index + 1 + "、";
    });
    itemIds = ids.value;
  }
  proxy.$modal
    .confirm('是否确认删除项目序号为"' + confirmText.slice(0, -1) + '"的数据项？')
    .then(function () {
      return delItem(itemIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};

const handQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  getList();
};

const getList = () => {
  loading.value = true;
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.startTime = dateRange.value[0] + " 00:00:00";
    queryParams.value.endTime = dateRange.value[1] + " 00:00:00";
  } else {
    queryParams.value.startTime = undefined;
    queryParams.value.endTime = undefined;
  }
  listItem(queryParams.value).then((res) => {
    itemList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  });
};

const handleCheckInfo = (row) => {
  getItemHospitalAssignments(row.id).then((res) => {
    currentHospitalInfo.value = res.data;
    hospitalInfoVisible.value = true;
  })
};

const handleAdd = () => {
  reset();
  title.value = "新增服务";
  open.value = true;
};

const handleUpdate = (row) => {
  reset();
  const id = row.id || ids.value;
  getItem(id).then((res) => {
    form.value = res.data;
    title.value = "修改服务";
    open.value = true;
  });
};

const submitForm = () => {
  proxy.$refs["itemRef"].validate((val) => {
    if (val) {
      if (form.value.id !== undefined) {
        updateItem(form.value).then((res) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addItem(form.value).then((res) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
};

const cancel = () => {
  open.value = false;
  reset();
};

const reset = () => {
  form.value = {
    id: undefined,
    name: undefined,
    avatar: undefined,
    description: undefined,
    serviceContent: undefined,
  };
  proxy.resetForm("itemRef");
};

const handleAssignHospital = (row) => {
  getItem(row.id).then((res) => {
    currentItem.value = res.data;
    assignHospitalVisible.value = true;
  });
};

const handleAssignHospitalSuccess = () => {
  proxy.$modal.msgSuccess('分配成功');
  hospitalInfoVisible.value = false;
};
const hospitalInfoClose = () => {
  hospitalInfoVisible.value = false;
};
const assignHospitalClose = () => {
  assignHospitalVisible.value = false;
  currentItem.value = {};
};

getList();
</script>
